package com.iecas.launch;

import com.iecas.enums.BizEnum;
import com.iecas.request.LoginReq;
import com.iecas.utils.RequestUtils;

import javax.swing.*;
import java.awt.*;
import java.nio.ByteBuffer;

public  class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JTextField errMeg;
    private JPasswordField passwordField;
    private JButton loginButton;
    Client client;

    public LoginFrame() {
        setTitle("Login");
        setLayout(new FlowLayout());
        this.setBounds(650, 400, 400, 200);
        errMeg = new JTextField(30);
        errMeg.setEditable(false);
        add(errMeg, FlowLayout.LEFT);
        errMeg.setText("这是提示信息");
        passwordField = new JPasswordField(30);
        add(passwordField, FlowLayout.LEFT);
        passwordField.setText("admin");
        usernameField = new JTextField(30);
        add(usernameField, FlowLayout.LEFT);
        usernameField.setText("admin");


        loginButton = new JButton("Login");
        loginButton.addActionListener(e -> {
            String username = usernameField.getText();
            String password = passwordField.getText();
            login(username, password);
        });
        add(loginButton, FlowLayout.LEFT);

        this.setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setResizable(false);
    }

    public void setErrMsg(String msg){
        errMeg.setText(msg);
    }

    public void setClient(Client client){
        this.client = client;
    }

    private void login(String username, String password) {
        try {
            LoginReq loginReq = new LoginReq();
            loginReq.setCode(BizEnum.LOGIN_REQ.getCode());
            loginReq.setUserName(username);
            loginReq.setPassword(password);
            ByteBuffer encode = RequestUtils.encode(loginReq);
            client.write(encode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
